import React, {useEffect, useState} from 'react';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {
  ProForm,
  ProFormSelect,
  ProFormText, ProFormTextArea
} from "@ant-design/pro-form";
import styles from './style.less';
import {Card, Col, Form, message, Row} from "antd";
import {CourseManager, OpCircleManager, UserManager} from "@/services/api-functions";
import UploadForm from "@/components/UploadForm";
import {CircleMod, OssPojo} from "@/services/api-types";
// @ts-ignore
import {history} from "umi";
import {SYS_ENUMS} from "@/utils/constants";


export const circleSaveOrUpdate = async (fields: any, select: any, cover: OssPojo|undefined) => {
  try {
    const rpo: CircleMod = {
      id: select?.id ?? '',
      title: fields.title,
      introduce: fields.introduce,
      circleType: fields.circleType,
      cover,
      circleBelongUserId: fields.circleBelongUserId,
    }

    if(fields.circleType === 'COURSE'){
      rpo.courseId = fields.courseId;
    }

    if (isSuccess((select && select.id ? (await OpCircleManager.mod(rpo)) : (await OpCircleManager.add(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

const CircleEdit: React.FC<any> = ({match: {params: {id}}}) => {

  const [formRef] = Form.useForm()
  const [circle, setCircle] = useState<any>(null);
  const [cover, setCover] = useState<OssPojo>();
  const [type, setType] = useState<'SIMPLE'|'COURSE'>('SIMPLE');


  const queryCircleDetail = (selectId: any) => {
    if (selectId) {
      OpCircleManager.detail(selectId).then(({code, data}) => {
        if (isSuccess(code)) {
          setCircle(data)
          if (data.cover) {
            setCover(data.cover)
          }
          if (data.circleType) {
            setType(data.circleType)
          }

          formRef?.setFieldsValue({
            title: data.title,
            circleBelongUserId: data.circleBelongUserDto?.userId,
            courseId: data.courseDto?.courseId,
            cover: data.cover ? [data.cover] : [],
            circleType: data.circleType,
            introduce: data.introduce,
          })
        }
      })
    }
  }

  useEffect(() => {
    queryCircleDetail(id)
  }, [id])

  const onFinish = async (values: Record<string, any>) => {
    if (await circleSaveOrUpdate(values, circle, cover)) {
      history.push('/circle/list')
    }
  };

  return (
    <ProForm
      layout="vertical"
      hideRequiredMark
      submitter={{render: (props, dom) =><FooterToolbar>{dom}</FooterToolbar>,}}
      form={formRef}
      initialValues={{}}
      onFinish={onFinish}
      onValuesChange={v => {
        if(v.circleType){
          setType(v.circleType)
        }
      }}
    >
      <PageContainer>
        <Card title={`${id?'编辑':'添加'}圈子`} className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormSelect label='圈主' name='circleBelongUserId' required rules={[{required: true, message: '请设置圈主',},]}
                             request={async (params) => {
                               const {code, data} = await UserManager.simpleUserQuery({
                                 current: 1,
                                 pageSize: 20,
                                 nickName: params.keyWords ?? '',
                               })
                               return isSuccess(code) ? (data.data ?? []).map((item: any) => {
                                 const {id, nickName, phone} = item
                                 return {label: `${nickName}(${phone ?? '暂无手机号'})`, value: id}
                               }) : []
                             }} showSearch/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect label='圈子类型' required rules={[{required: true, message: '请填选择圈子类型',},]} name='circleType'
                             initialValue={'SIMPLE'}
                             options={Object.values(SYS_ENUMS.CIRCLE_TYPE)}/>
            </Col>
          </Row>
          {
            type === 'COURSE' && <Row gutter={16}>
              <Col lg={12} md={12} sm={24}>
                <ProFormSelect label='关联课程' name='courseId' required rules={[{required: true, message: '请选择关联课程',},]}
                               request={async (params) => {
                                 const {code, data} = await CourseManager.list({
                                   current: 1,
                                   pageSize: 20,
                                   title: params.keyWords ?? '',
                                 })
                                 return isSuccess(code) ? (data.data ?? []).map((item: any) => {
                                   const {id, title} = item
                                   return {label: title, value: id}
                                 }) : []
                               }} showSearch/>
              </Col>
            </Row>
          }
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormText label='圈子标题' required rules={[{required: true, message: '请填写圈子标题',},]} name="title"/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormTextArea label='圈子简介' required rules={[{required: true, message: '请输入圈子简介',},]} name='introduce'/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm label='封面' name='cover' type='public' max={1} rules={[{required: true, message: '请上传封面',},]} required={true}
                          accept='.jpg,.jpeg,.bmp,.gif,.png' success={file => setCover(file)}
                          remove={() => setCover(undefined)}/>
            </Col>
          </Row>
        </Card>
      </PageContainer>
    </ProForm>
  );
};

export default CircleEdit;
